/**
 * 
 */
package ua.ws.feedsreader.db;

import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.http.HTTPRepository;

/**
 * @author ricardo
 *
 */
public class ConnectionManager {

	private String sesameServer = "http://localhost:8080/openrdf-sesame";
	private String repositoryID = "Feeds";
	private Repository myRepository;
	private RepositoryConnection connection;

	public ConnectionManager() {
		myRepository = new HTTPRepository(sesameServer, repositoryID);                
	}

	public void initialize() throws RepositoryException {
		if( myRepository == null ) {
			throw new NullPointerException("O MyRepository encontra-se vazio");
		}
		myRepository.initialize();
	}

	public RepositoryConnection getConnection() throws RepositoryException {
		if( myRepository == null ) {
			throw new NullPointerException("O MyRepository encontra-se vazio");
		}
		
		if(connection == null || !connection.isOpen() ) {
			connection = myRepository.getConnection();			
		}
		
		return connection;
	}

	public void closeConnection() throws RepositoryException {
		if( connection != null && connection.isOpen() ) {
			connection.close();
		}
	}
	
	public void shutdown() throws RepositoryException {
		if( myRepository == null ) {
			throw new NullPointerException("O MyRepository encontra-se vazio");
		}
		myRepository.shutDown();
	}

	/**
	 * @return the myRepository
	 */
	public Repository getMyRepository() {
		return myRepository;
	}

}
